#include <iostream>
#include <memory>
#include "tcp_server.hpp"
#include "Protocol.hpp"

using namespace std;
using namespace ns_server;

ns_protocol::Response func(const ns_protocol::Request& req)
{
    //计算
    int result = 0;
    int code = 0;

    switch(req.getOP())
    {
        case '+':
            result = req.getX() + req.getY();
        break;
        case '-':
            result = req.getX() - req.getY();
        break;
        case '*':
            result = req.getX() * req.getY();
        break;
        case '/':
            if(req.getY() == 0)
                code = 1;
            else
                result = req.getX() / req.getY();
        break;
        case '%':
            if(req.getY() == 0)
                code = 2;
            else
                result = req.getX() % req.getY();
        break;
        default:
            code = 3;   //未知运算符
        break;
    }

    return ns_protocol::Response(result, code);
}

void Usage(const char* porc)
{
    cout << "Usage:" << endl;
    cout << "\t" << porc << " Port" << endl; 
}

int main(int argc, char* argv[])
{
    uint16_t port;
    if(argc != 2)
    {
        cout << "参数传递有误，已按默认设定进行连接" << endl;
        Usage(argv[0]);
        port = default_port;
    }
    else
    {
        port = stoi(argv[1]);
    }

    unique_ptr<TcpServer> tsvr(new TcpServer(func, port));

    tsvr->InitServer();
    tsvr->StartServer();

    return 0;
}